exports.save = function(vehicleId, fillUpId) {
	
	// We used to have a caching table called vehicle_consumption, however we no longer use it.
	var consumptions = exports.findByVehicleID(vehicleId);
	
	var consumptions_sum = 0;
	for(var i = 0, l = consumptions.length; i < l; i++) {
		consumptions_sum += consumptions[i];
	}
	var avgcons = consumptions_sum / consumptions.length;
	
	return avgcons;
}

exports.findByVehicleID = function(vehicleId) {
	
	var Database = require('/database/Database');
	var db = new Database();

	var resultRows = db.execute(
		'select vf.id, vehicle_odometer, fillup_date, fillup_units, belongs_to_fillup ' + 
		'from vehicle_fillup vf where vf.vehicleId=?',
		vehicleId
	);
	
	var fillups = [];
	var partials = {};
	
	while(resultRows.isValidRow()) {
		var fillup_id = resultRows.fieldByName('id');
		var vehicle_odometer = resultRows.fieldByName('vehicle_odometer');
		var fillup_date = resultRows.fieldByName('fillup_date');
		var fillup_units = resultRows.fieldByName('fillup_units');
		var belongs_to_fillup = resultRows.fieldByName('belongs_to_fillup');
	
		// If we hit a partial and it doesn't point anywhere, this must be the last fillup
		if(belongs_to_fillup == 0) {
			break;
		}
		
		if(belongs_to_fillup != null) {
			if(!(belongs_to_fillup in partials)) {
				partials[belongs_to_fillup] = 0.0;
			}	
			partials[belongs_to_fillup] += fillup_units;
		} else {
			var partial_fillup_units = 0.0;
			if(fillup_id in partials) {
				partial_fillup_units = partials[fillup_id];
			}
			
			fillups.push([vehicle_odometer, partial_fillup_units + fillup_units, fillup_date]);
		}
			
		resultRows.next();
	}
	
	var previous_odometer = null, previous_fillup_units = null;
	var consumptions = [];
	
	for(var i = 0; i < fillups.length; i++) {
		
		if(previous_odometer != null && previous_fillup_units != null) {
			var current_odometer = fillups[i][0];
			var current_fillup_units = fillups[i][1];
			var current_fillup_date = fillups[i][2];
			
			var fuelcons = current_fillup_units / (current_odometer - previous_odometer);
			
			// Add to consumptions in order to calculate average later
			consumptions.push([current_fillup_date, fuelcons*100]);
		}
		
		previous_odometer = fillups[i][0];
		previous_fillup_units = fillups[i][1];
	}
	
	return consumptions;
}